package cn.otrue.patienthealthmanager.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.DrugAddListAdpater;
import cn.otrue.patienthealthmanager.adapter.TextAdapter;
import cn.otrue.patienthealthmanager.bean.DrugPlanModel;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.MyGridView;
import cn.otrue.patienthealthmanager.view.SwitchButton;

/**
 * 主页->健康计划->用药管理
 * 
 * @author G
 * 
 */
public class DrugManagerActivity extends BaseActivity implements
		OnItemClickListener {

	private TextView tv_title_back;
	private TextView tv_title_title;

	private List<DrugPlanModel> drugData = new ArrayList<DrugPlanModel>();

	private ListView lv_drug_manager_list;
	private DrugAddListAdpater adapter;
	private TextView tv_drug_manager_add;
	private String drugStr = "";
	private String beginTime = "";
	private String endTime = "";
	private List<Map<String, String>> weekData = new ArrayList<Map<String, String>>();
	private TextView tv_title_other;
	private MyGridView gv_drug_week;
	private TextAdapter weekAdapter;

	// 闹钟
	private SwitchButton sb_drug_manager_colock;

	// 开始时间选择框
	private DatePickerDialog beginDateDialog;
	// 结束时间选择框
	private DatePickerDialog endDateDialog;
	// 开始时间
	private Calendar beginCalendar = Calendar.getInstance();
	// 结束时间
	private Calendar endCalendar = Calendar.getInstance();
	private SimpleDateFormat sdf;
	private Handler drugHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("Plan", dataStr);
				drugStr = dataStr;
			} else {

			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_drug_manager);
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		getData();
		initView();

	}

	private void getDrugData() {
		// 得到药品
		HashMap<String, Object> map = new HashMap<String, Object>();
		TransferParameter parameter = new TransferParameter();
		parameter.setCurrentPage("1");
		parameter.setPagesize("20");
		parameter.setData(map);
		new HttpServer().post(HttpCons.QUERY_DRUG_TYPE, parameter, drugHandler);

	}

	private void getData() {
		getDrugData();
		Intent intent = getIntent();

		type = intent.getIntExtra("type", -1);
		String data = intent.getStringExtra("data");
		if (!TextUtils.isEmpty(data)) {
			drugPlan = HttpServer.gson.fromJson(data, DrugPlanModel.class);
			drugData.add(drugPlan);
		}

		for (int i = 0; i < 7; i++) {
			Map<String, String> week = new HashMap<String, String>();
			week.put("diseasename", MyConst.WEEK[i]);
			week.put("weekid", i + "");
			week.put("state", "0");
			weekData.add(week);
		}
		if (drugData.size() > 0 && drugPlan.getWeekList() != null) {
			for (int i = 0; i < drugPlan.getWeekList().size(); i++) {
				int eachOne = Integer.parseInt(drugPlan.getWeekList().get(i));
				for (int j = 0; j < weekData.size(); j++) {
					if (eachOne == Integer.parseInt(weekData.get(j).get(
							"weekid"))) {
						weekData.get(j).put("state", "1");
					}
				}
			}
		}

	}

	private void initView() {
		initTitleBar();
		tv_drug_manager_add = (TextView) findViewById(R.id.tv_drug_manager_add);
		lv_drug_manager_list = (ListView) findViewById(R.id.lv_drug_manager_list);
		et_drug_begin_time = (EditText) findViewById(R.id.et_drug_begin_time);
		et_drug_end_time = (EditText) findViewById(R.id.et_drug_end_time);
		sb_drug_manager_colock = (SwitchButton) findViewById(R.id.sb_drug_manager_colock);
		gv_drug_week = (MyGridView) findViewById(R.id.gv_drug_week);
		et_drug_manager_note = (EditText) findViewById(R.id.et_drug_manager_note);
		tv_drug_manager_note = (TextView) findViewById(R.id.tv_drug_manager_note);
		et_drug_begin_time.setOnClickListener(this);
		et_drug_end_time.setOnClickListener(this);
		switch (type) {
		case MyConst.BLANK_PLAN:
		case MyConst.CHANGE_PLAN:
			tv_drug_manager_add.setVisibility(View.VISIBLE);
			et_drug_manager_note.setVisibility(View.VISIBLE);
			tv_drug_manager_note.setVisibility(View.GONE);

			gv_drug_week.setOnItemClickListener(this);
			tv_drug_manager_add.setOnClickListener(this);

			if (drugData.size() != 0
					&& !TextUtils.isEmpty(drugData.get(0).getNote())) {
				et_drug_manager_note.setText(drugData.get(0).getNote());
			}

			break;
		case -1:
		case MyConst.SHOW_PLAN:
			et_drug_begin_time.setOnClickListener(null);
			et_drug_end_time.setOnClickListener(null);
			tv_drug_manager_add.setVisibility(View.GONE);
			et_drug_manager_note.setVisibility(View.GONE);
			tv_drug_manager_note.setVisibility(View.VISIBLE);
			tv_title_other.setVisibility(View.GONE);
			if (drugData.size() != 0
					&& !TextUtils.isEmpty(drugData.get(0).getNote())) {
				tv_drug_manager_note.setText(drugData.get(0).getNote());
			}
			break;
		}

		if (drugData.size() == 1) {
			tv_drug_manager_add.setVisibility(View.GONE);
			adapter = new DrugAddListAdpater(drugData, this, false);
			try {
				String drugbegintime = drugData.get(0).getDrugbegintime();
				String drugendtime = drugData.get(0).getDrugendtime();
				if (!TextUtils.isEmpty(drugbegintime)
						&& !TextUtils.isEmpty(drugendtime)) {
					et_drug_begin_time.setText(drugbegintime.substring(0, 10));
					et_drug_end_time.setText(drugendtime.substring(5, 10));
					beginTime = drugbegintime;
					endTime = drugendtime;
					beginCalendar.setTime(sdf.parse(drugbegintime));
					endCalendar.setTime(sdf.parse(drugendtime));
				}

				for (int i = 0; i < drugData.get(0).getWeekList().size(); i++) {
					int eachOne = Integer.parseInt(drugData.get(0)
							.getWeekList().get(i));
					for (int j = 0; j < weekData.size(); j++) {
						if (eachOne == Integer.parseInt(weekData.get(j).get(
								"weekid"))) {
							weekData.get(j).put("state", "1");
						}
					}
				}

			} catch (ParseException e) {

			}

		} else {
			adapter = new DrugAddListAdpater(drugData, this, true);
		}

		sb_drug_manager_colock.setOnClickListener(this);
		weekAdapter = new TextAdapter(this, weekData);
		gv_drug_week.setAdapter(weekAdapter);
		// 去掉点击时出现的默认边框
		gv_drug_week.setSelector(new ColorDrawable(Color.TRANSPARENT));

		lv_drug_manager_list.setAdapter(adapter);

		lv_drug_manager_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(DrugManagerActivity.this,
						DialogGrugActivity.class);
				intent.putExtra("drugStr", drugStr);
				startActivityForResult(intent, arg2);

			}

		});

	}

	private void initTitleBar() {

		tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		tv_title_back.setVisibility(View.VISIBLE);
		tv_title_back.setOnClickListener(this);
		tv_title_title = (TextView) findViewById(R.id.tv_title_title);
		tv_title_title.setText(getString(R.string.drug_manager));
		tv_title_other = (TextView) findViewById(R.id.tv_title_other);
		tv_title_other.setVisibility(View.VISIBLE);
		tv_title_other.setOnClickListener(this);
		tv_title_other.setText(getString(R.string.community_fatie));

	}

	@Override
	public void onClick(View arg0) {
		Intent intent = new Intent();
		switch (arg0.getId()) {
		case R.id.tv_title_back:
			finish();
			break;

		case R.id.tv_title_other:
			resultData();
			break;

		case R.id.et_drug_begin_time:

			beginDateDialog = new DatePickerDialog(this, BeginDateSet,
					beginCalendar.get(Calendar.YEAR),
					beginCalendar.get(Calendar.MONTH),
					beginCalendar.get(Calendar.DAY_OF_MONTH));
			beginDateDialog.setTitle("开始时间");
			beginDateDialog.show();

			break;
		case R.id.et_drug_end_time:
			endDateDialog = new DatePickerDialog(this, EndDateSet,
					endCalendar.get(Calendar.YEAR),
					endCalendar.get(Calendar.MONTH),
					endCalendar.get(Calendar.DAY_OF_MONTH));
			endDateDialog.setTitle("结束时间");
			endDateDialog.show();

			break;

		case R.id.tv_drug_manager_add:
			if (!TextUtils.isEmpty(drugStr)) {
				intent = new Intent(this, DialogGrugActivity.class);
				intent.putExtra("drugStr", drugStr);
				startActivityForResult(intent, 999);
			} else {
				Toast.makeText(this, "药品为空", 0).show();
			}
			break;
		case R.id.sb_drug_manager_colock:
			sb_drug_manager_colock.changeOpen();
			break;
		default:
			break;
		}

	}

	private void resultData() {

		List<String> weekList = new ArrayList<String>();
		for (int i = 0; i < weekData.size(); i++) {
			if (weekData.get(i).get("state").equals("1")) {
				weekList.add(weekData.get(i).get("weekid").toString());
			}
		}

		if (TextUtils.isEmpty(beginTime)) {
			Toast.makeText(this, "请选择开始时间", 0).show();
		} else if (TextUtils.isEmpty(endTime)) {
			Toast.makeText(this, "请选择结束时间", 0).show();
		} else if (drugData.size() == 0) {
			Toast.makeText(this, "请选择药品", 0).show();
		} else if (weekList.size() < 1) {
			Toast.makeText(this, "请选择重复时间", 0).show();
		} else {

			for (int i = 0; i < drugData.size(); i++) {
				drugData.get(i).setWeekList(weekList);
				drugData.get(i).setDrugbegintime(beginTime);
				drugData.get(i).setDrugendtime(endTime);
				if (!TextUtils.isEmpty(et_drug_manager_note.getText())) {
					drugData.get(i).setNote(
							et_drug_manager_note.getText().toString());
				} else {
					drugData.get(i).setNote("暂无");
				}
			}

			Intent intent = new Intent();
			intent.putExtra("drugData", HttpServer.gson.toJson(drugData));
			setResult(MyConst.DRUG_RESULT, intent);
			finish();
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {

		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 != 999) {
			String[] results = arg2.getStringArrayExtra("results");
			DrugPlanModel drug = new DrugPlanModel();
			drug.setDrugid(results[0]);
			drug.setDrugName(results[1]);
			drug.setDrugfrequency(results[2]);
			drug.setDrugdose(results[3]);
			drug.setBreakfast(results[4]);
			drugData.set(arg0, drug);
			adapter.notifyDataSetChanged();
		} else {
			if (arg1 == 1) {
				String[] results = arg2.getStringArrayExtra("results");
				DrugPlanModel drug = new DrugPlanModel();
				drug.setDrugid(results[0]);
				drug.setDrugName(results[1]);
				drug.setDrugfrequency(results[2]);
				drug.setDrugdose(results[3]);
				drug.setBreakfast(results[4]);
				drugData.add(drug);
				adapter.notifyDataSetChanged();
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String state = weekData.get(position).get("state");
		if (TextUtils.isEmpty(state) || state.equals("0")) {
			weekData.get(position).put("state", "1");
		} else {
			weekData.get(position).put("state", "0");
		}

		weekAdapter.notifyDataSetChanged();

	}

	DatePickerDialog.OnDateSetListener BeginDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 每次保存设置的日期

			beginCalendar.set(Calendar.YEAR, year);
			beginCalendar.set(Calendar.MONTH, monthOfYear);
			beginCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			beginTime = year + "-" + timeFormat(monthOfYear + 1) + "-"
					+ timeFormat(dayOfMonth);
			et_drug_begin_time.setText(beginTime);

		}
	};

	DatePickerDialog.OnDateSetListener EndDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			int byear = beginCalendar.get(Calendar.YEAR);
			int bmonth = beginCalendar.get(Calendar.MONTH);
			int bday = beginCalendar.get(Calendar.DAY_OF_MONTH);

			if ((byear * 365 + bmonth * 30 + bday) >= (year * 365 + monthOfYear
					* 30 + dayOfMonth)) {
				Toast.makeText(DrugManagerActivity.this, "结束时间不能小于起始时间", 0)
						.show();
				beginCalendar = Calendar.getInstance();
				endCalendar = Calendar.getInstance();
				et_drug_begin_time.setText("");
				et_drug_end_time.setText("");

			} else {
				endCalendar.set(Calendar.YEAR, year);
				endCalendar.set(Calendar.MONTH, monthOfYear);
				endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				beginTime = byear + "-" + timeFormat(bmonth + 1) + "-"
						+ timeFormat(bday);
				endTime = year + "-" + timeFormat(monthOfYear + 1) + "-"
						+ timeFormat(dayOfMonth);
				et_drug_begin_time.setText(beginTime);
				et_drug_end_time.setText(timeFormat(monthOfYear + 1) + "-"
						+ timeFormat(dayOfMonth));

			}

		}
	};
	private int type;
	private EditText et_drug_manager_note;
	private TextView tv_drug_manager_note;
	private DrugPlanModel drugPlan;
	private EditText et_drug_begin_time;
	private EditText et_drug_end_time;

	private String timeFormat(int time) {
		if (time < 10) {
			return "0" + time;
		}
		return time + "";
	}

}
